/**
 * @desc 权限列表组件
 * */
import React from "react";
import { connect } from "react-redux";
import { Space, Button } from "antd";
import { apiRoleList, apiRoleToMenu, apiRoleMenuByRoleId } from "@/request/system/role";
import { apiRoleWithIdent } from "@/request/system/menu"
import "./style/style.less"
import { getTreeData } from "@/utils/getTreeData"
import _ from 'lodash'
import TheButton from "@/components/TheButton";

class Authority extends React.Component {
  //定义表单ref
  state = {
    roleList: [],
    roleId: '',
    menuList: [],
    menuId: [],
    loading: false,
    columns: [
      {
        title: '权限名称',
        dataIndex: 'menuName'
      }
    ],
    treeData: [],
    selectedRowKeys: [],
    checkList: [],
    indentList: []
  };

  async componentDidMount() {
    await this.getRoleList()
  }

  /**
   * @desc 获取菜单信息
   * */
  getMenus = () => {
    apiRoleWithIdent().then(res => {
      if (res.code === 0) {
        this.setState({
          menuList: getTreeData(this.setCheckData(res.data))
        }, () => {
        })
      }
    })
  }
  /**
   * @desc 根据角色返回值设置菜单数据
   * @params data {Array} 需要遍历的数组
   * @return Array 返回一个重组后的数组
   * */
  setCheckData = (data) => {
    const checkList = [...this.state.checkList];
    const indentList = [...this.state.indentList];
    const result = data.map(v => {
      v.identId = v.menuId;
      v.key = v.menuId;
      v.isChecked = checkList.includes(v.identId);
      if (v.sysIdentList.length > 0) {
        v.sysIdentList.map(m => {
          m.key = m.identId;
          m.isChecked = indentList.includes(m.identId);
          m.menuName = m.identName
          return m
        })
      }
      return v
    })
    return result
  }
  /**
   * @desc 获取角色列表
   * */
  getRoleList = async () => {
    const res = await apiRoleList({ pageNo: 1, pageSize: 1000, status: 'Y' });
    if (res.code === 0 && res.data) {
      if (res.data.length > 0) {
        const data = res.data.map(v => {
          return {
            label: v.roleName === 'STORE' ? '门店管理员' : v.roleName,
            value: v.roleId
          }
        })
        this.setState({ roleList: data, roleId: data[0].value }, () => {
          this.getRoleMenuByRoleId()
        })
      }
    }
  }
  /**
   * @desc 获取角色关联菜单
   * */
  getRoleMenuByRoleId = async () => {
    const res = await apiRoleMenuByRoleId({ roleId: this.state.roleId });
    if (res.code !== 0) return;
    this.getMenus()
    // todo 待后台修改完数据结构后打开
    this.setState({
      checkList: res.data.menus.map(v => v.menuId),
      indentList: res.data.idents.map(v => v.identId)
    }, () => {
      // this.getMenus()
    })
  }
  /**
   * @desc 顶部角色选择事件
   * */
  onChange = (e) => {
    console.log(e);
    this.setState({ roleId: e }, () => {
      this.getRoleMenuByRoleId()
    })
  }

  /*    
      将item扁平化，
      currentDeep 初始深度，
      depth 目标深度，默认无限，
      context 初始context
      */
  flattenItem = (item, currentDeep = 0, depth, context = []) => {
    item.deep = currentDeep;
    item.context = context;
    if (item.children && currentDeep !== depth) {
      return item.children.map((child, index) => this.flattenItem(child, currentDeep + 1, depth, [...context, index])).flat();
    } else {
      return [item];
    }
  }

  /**
   * @desc 一级权限选中事件
   * @params number {i} 修改的索引
   * */
  changeOneLevel = (e, i) => {
    const menuList = [...this.state.menuList];
    menuList[i].isChecked = !menuList[i].isChecked;
    const setArrIsChecked = (list) => {
      if (list.hasOwnProperty('children') && list.children.length > 0) {
        list.children.forEach(m => {
          m.isChecked = menuList[i].isChecked;
          setArrIsChecked(m)
        })
      } else {
        list.sysIdentList.forEach(m => {
          m.isChecked = menuList[i].isChecked;
        })
      }
    }
    setArrIsChecked(menuList[i])
    this.setState({ menuList })
  }

  /**
   * @desc 二级权限选中事件
   * @params number {i} 一级修改的索引
   * @params number {n} 二级修改的索引
   * */
  changeTwoLevel = (e, i, n) => {
    const menuList = [...this.state.menuList];
    const indentList = [...this.state.indentList];
    const flag = !menuList[i].children[n].isChecked;
    menuList[i].children[n].isChecked = flag
    if (flag) {
      menuList[i].isChecked = true;
    } else {
      const bl = menuList[i].children.some(item => item.isChecked)
      if (!bl) menuList[i].isChecked = bl;
    }
    const list = menuList[i].children[n]
    const setArrIsChecked = (list) => {
      if (list.hasOwnProperty('children') && list.children.length > 0) {
        list.children.forEach(m => {
          m.isChecked = flag;
          setArrIsChecked(m)
        })
      } else {
        let indent = []
        list.sysIdentList.forEach(m => {
          m.isChecked = flag;
          if (!m.isChecked) indent.push(m.identId)
        })
        indentList.filter(i => {
          return !indent.includes(i)
        })
      }
    }
    setArrIsChecked(list)
    this.setState({ menuList, indentList })
  }
  //三级菜单选择
  changeMenuThrLevel = (e, i, n, j) => {
    const menuList = [...this.state.menuList];
    const indentList = [...this.state.indentList];
    const flag = !menuList[i].children[n].children[j].isChecked;
    menuList[i].children[n].children[j].isChecked = flag
    if (flag) {
      menuList[i].children[n].isChecked = flag
      menuList[i].isChecked = flag
    } else {
      const bl = menuList[i].children[n].children.some(item => {
        return item.isChecked == true
      })
      if (!bl) {
        menuList[i].children[n].isChecked = false
        const firstFlag = menuList[i].children.some(item => {
          return item.isChecked == true
        })
        if (!firstFlag) menuList[i].isChecked = false
      }
    }
    const list = menuList[i].children[n].children[j]
    const setArrIsChecked = (list) => {
      if (list.hasOwnProperty('children') && list.children.length > 0) {
        list.children.forEach(m => {
          m.isChecked = menuList[i].isChecked;
          setArrIsChecked(m)
        })
      } else {
        list.sysIdentList.forEach(m => {
          m.isChecked = flag;
          if (m.isChecked) {
            indentList.push(m.identId)
          }
        })
      }
    }
    setArrIsChecked(list)
    this.setState({ menuList, indentList })
  }

  /**
  * @desc 三级权限选中事件
  * @params number {i} 一级修改的索引
  * @params number {n} 二级修改的索引
  * @params number {j} 三级修改的索引
  * */
  changeThrLevel = (e, i, n, j) => {
    const menuList = [...this.state.menuList];
    let indentList = [...this.state.indentList];
    menuList[i].children[n].sysIdentList[j].isChecked = !menuList[i].children[n].sysIdentList[j].isChecked;
    if (menuList[i].children[n].sysIdentList[j].isChecked) {
      indentList.push(menuList[i].children[n].sysIdentList[j].identId);
    } else {
      indentList = indentList.filter(v => v !== menuList[i].children[n].sysIdentList[j].identId);

    }
    if (menuList[i].children[n].sysIdentList[j].isChecked) {
      menuList[i].isChecked = true;
      menuList[i].children[n].isChecked = true;
    }
    this.setState({ menuList, indentList })
  }


  /**
   * @desc 四级权限选中事件
   * @params number {i} 一级修改的索引
   * @params number {n} 二级修改的索引
   * @params number {j} 三级修改的索引
   * @params number {f} 四级修改的索引
   * */
  changeFourLevel = (e, i, n, j, f) => {
    const menuList = [...this.state.menuList];
    let indentList = [...this.state.indentList];
    menuList[i].children[n].children[j].sysIdentList[f].isChecked = !menuList[i].children[n].children[j].sysIdentList[f].isChecked;
    if (menuList[i].children[n].children[j].sysIdentList[f].isChecked) {
      indentList.push(menuList[i].children[n].children[j].sysIdentList[f].identId);
    } else {
      indentList = indentList.filter(v => v !== menuList[i].children[n].children[j].sysIdentList[f].identId);
    }
    if (menuList[i].children[n].children[j].sysIdentList[f].isChecked) {
      menuList[i].isChecked = true;
      menuList[i].children[n].children[j].isChecked = true;
      menuList[i].children[n].isChecked = true;
    }
    this.setState({ menuList, indentList })
  }

  /***
   * @desc 递归获取数据
   *
   * */
  recursiveData = (arr, data) => {
    let result = data || [];
    if (!Array.isArray(arr)) return;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].isChecked) {
        result.push(arr[i].identId)
      }
      if (arr[i].children) {
        result = this.recursiveData(arr[i].children, result)
      }
    }
    return result
  }
  /**
   * @desc 权限保存事件
   * */
  save = () => {
    this.setState({ loading: true })
    let menuIds = this.recursiveData(this.state.menuList)
    let indentIds = []
    _.flattenDeep(this.state.menuList.map(v => {
      if (v.children) {
        return v.children.map(item => {
          if (item.children) {
            item.children.map(items => {
              let temp = items.sysIdentList.filter(value => {
                return value.isChecked
              }).map(v => v.identId)
              indentIds.push(...temp)
            })
          } else {
            let temp = item.sysIdentList.filter(value => {
              return value.isChecked
            }).map(v => v.identId)
            indentIds.push(...temp)
          }
          return item
        })
      } else {
        return []
      }
    }))

    // indentIds = indentIds.length ? indentIds.map(v => v.identId) : []
    if (!this.state.roleId) {
      this.setState({ loading: false })
      return React.$message({
        type: 'error',
        content: '请选择角色'
      })
    }
    if (menuIds.length <= 0) {
      this.setState({ loading: false })
      return React.$message({
        type: 'error',
        content: '请选择菜单权限'
      })
    }
    // if (indentIds.length <= 0) {
    //   this.setState({ loading: false })
    //   return React.$message({
    //     type: 'error',
    //     content: '请选择按钮权限'
    //   })
    // }
    apiRoleToMenu({
      roleId: this.state.roleId,
      menuIds: menuIds,
      identIds: indentIds
    }).then(res => {
      if (res.code === 0) {
        React.$message({
          type: 'success',
          content: '保存成功'
        })
        this.getRoleMenuByRoleId()
      }
      this.setState({ loading: false })
    }).catch(e => {
      this.setState({ loading: false })
    })
  }

  render() {

    let { roleList, menuList, roleId, loading } = this.state;
    return (
      <div className={"p-layout-box"}>
        {/*顶部搜索区域*/}
        <div className={"p-search-box"}>
          <div>
            <span>选择角色：</span>
            <React.FormSelect key={roleId} options={roleList} value={roleId}
              onChange={this.onChange}
              style={{ width: 200 }}
              placeholder={'请选择用户'} />
          </div>

        </div>
        {/*表格区域*/}
        <div className={"p-layout-content"}>
          <div className='auth-tree-wrap'>
            {
              menuList.map((v, i) => {
                return <div className='auth-tree-box' key={i}>
                  <div className='auth-tree-top'>
                    <React.FormCheckbox onChange={(e) => this.changeOneLevel(e, i)}
                      checked={v.isChecked} />
                    <em>{v.menuName}</em>
                  </div>
                  <div className='auth-tree-oneLevel'>
                    <ul className='auth-tree-children auth-tree-children'>
                      {
                        v.children && v.children.length > 0 && v.children.map((m, n) => {
                          return <li key={m.menuId}>
                            <div>
                              <React.FormCheckbox
                                onChange={(e) => this.changeTwoLevel(e, i, n)}
                                checked={m.isChecked} />
                              <em>{m.menuName}</em>
                            </div>

                            {!!m.children ?
                              <>
                                {m.children && m.children.length > 0 && m.children.map((m, ne) => {
                                  return <div>
                                    <div style={{ marginLeft: '50px' }}>
                                      <React.FormCheckbox
                                        onChange={(e) => this.changeMenuThrLevel(e, i, n, ne)}
                                        checked={m.isChecked} />
                                      <em>{m.menuName}</em>
                                    </div>
                                    <ul className='auth-tree-children auth-tree-children2' style={{ marginLeft: '60px' }}>
                                      {
                                        m.sysIdentList && m.sysIdentList.length > 0 && m.sysIdentList.map((k, f) => {
                                          return <li key={k.identId}>
                                            <React.FormCheckbox
                                              onChange={(e) => this.changeFourLevel(e, i, n, ne, f)}
                                              checked={k.isChecked} />
                                            <em>{k.identName}</em>
                                          </li>
                                        })
                                      }
                                    </ul>
                                  </div>
                                })}
                              </>
                              :
                              <ul className='auth-tree-children auth-tree-children2'>
                                {
                                  m.sysIdentList && m.sysIdentList.length > 0 && m.sysIdentList.map((k, j) => {
                                    return <li key={k.identId} >
                                      <React.FormCheckbox
                                        onChange={(e) => this.changeThrLevel(e, i, n, j)}
                                        checked={k.isChecked} />
                                      <em>{k.identName}</em>
                                    </li>
                                  })
                                }
                              </ul>
                            }
                          </li>
                        })
                      }
                    </ul>
                  </div>
                </div>
              })
            }

            {/*  <TheTable rowSelection={{ ...rowSelection }} columns={columns} dataSource={treeData}/>*/}
          </div>
        </div>
        {/*分页区域*/}
        <div className={"p-page-box"}>
          <Space>
            <TheButton size="middle" hasPernmi={['set:power:save']} loading={loading} onClick={this.save} type="primary">
              保存
            </TheButton>
          </Space>
        </div>
      </div >
    );
  }
}

const mapStateToProps = state => {
  return {
    user: state.user
  };
};
export default connect(mapStateToProps, null)(Authority);
